import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
let lifeData = {}

try {
	lifeData = uni.getStorageSync('lifeData')
} catch (e) {

}

let saveStateKeys = ['vuex_user']

const saveLifeData = function (key, value) {
	if (saveStateKeys.indexOf(key) != -1) {
		let tmpLifeData = uni.getStorageSync('lifeData')
		tmpLifeData = tmpLifeData ? tmpLifeData : {},
		tmpLifeData[key] = value
		uni.setStorageSync('lifeData', tmpLifeData)
	}
}

const store = new Vuex.Store({
	state: {
		vuex_user: lifeData.vuex_user ? lifeData.vuex_user : {
			name: '学创校园'
		},
		vuex_version: "1.0.0",
		vuex_custom_nav_bar: true,
		vuex_status_bar_height: 0,
		vuex_custom_bar_height: 0,
		token: uni.getStorageSync('token') ? uni.getStorageSync('token') : null,
		userInfo: uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo') : null,
		isLogin: uni.getStorageSync('login') ? true : false,
	},
	mutations: {
		MLOGIN(state, token) {
			state.token = token
			state.isLogin = true
			uni.setStorageSync('token', token)
			uni.setStorageSync('login', true)
		},
		MLOGOUT(state) {
			state.token = null
			state.isLogin = false
			uni.removeStorageSync('token')
			uni.removeStorageSync('login')
		},
		MSETUSERINFO(state, userInfo) {
			state.userInfo = userInfo
			uni.setStorageSync('userInfo', userInfo)
		},
		$tStore(state, payload) {
			let nameArr = payload.name.split('.')
			let saveKey = ''
			let len = nameArr.length
			if (len >= 2) {
				let obj = state[nameArr[0]]
				for (let i = 1; i < len - 1; i++) {
					obj = obj[nameArr[i]]
				}
				obj[nameArr[len - 1]] = payload.value
				saveKey = nameArr[0]
			} else {
				state[payload.name] = payload.value
				saveKey = payload.name
			}
			saveLifeData(saveKey, state[saveKey])
		}
	},
	getters: {
		getToken: state => state.token,
		getUserInfo: state => state.userInfo,
		isLogin: state => state.isLogin
	}
})

Vue.prototype.$store = store
export default store